﻿using UnityEngine;

public class InputHandler : ActionController
{
    private Pointer pointer;        //辅助瞄准的箭头

    public bool b_testMode;         //是否处于调试模式
    [SerializeField]
    private bool b_isActive;        //是否接收输入

    [HideInInspector]
    private Vector3 mousePos;
    private bool _IsAiming;
    //是否在瞄准
    private bool IsAiming
    {
        get => _IsAiming;
        set
        {
            _IsAiming = value;
            pointer.Active = value;
        }
    }

    protected override void OnStart()
    {
        pointer = GetComponentInChildren<Pointer>();
        pointer.Active = false;
        pointer.Direction = new Vector2(mousePos.x - transform_player.position.x, mousePos.y - transform_player.position.y).normalized;

        eventSystem.AfterSceneLoad += OnAfterSceneLoad;
        eventSystem.CameraMove += SetActive;
        eventSystem.PlayerDie += MyReset;
    }

    private void OnAfterSceneLoad(int sceneIndex)
    {
        MyReset();
        b_isActive = sceneIndex > 0 && sceneIndex < SceneController.Index_Boot;
    }

    private void SetActive(bool active)
    {
        MyReset();
        b_isActive = !active;
    }

    private void MyReset()
    {
        IsAiming = false;
        pointer.Active = false;
        player.drct_move_input = 0;
        player.b_wantJump = false;
        player.b_wantDash = false;
        Time.timeScale = 1f;
    }

    private void Update()
    {
        if (!b_isActive)
            return;

        mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        mousePos -= new Vector3(0, 0, mousePos.z);
        player.drct_aim = new Vector2(mousePos.x - transform_player.position.x, mousePos.y - transform_player.position.y).normalized;
        pointer.Direction = player.drct_aim;

        if (b_testMode) 
        {
            if (Input.GetMouseButtonDown(3))
                player.Energy = 3;
            else if (Input.GetMouseButtonDown(2))
                Service.Get<SceneController>().LoadNextLevel();
        }

        if (!b_isActive || player.b_died)
            return;

        player.drct_move_input = Input.GetAxisRaw("Horizontal");
        if (Input.GetButtonDown("Jump"))
        {
            player.b_wantJump = true;
        }

        if (Input.GetMouseButtonDown(0) && player.Energy > 0 && !IsAiming)
        {
            IsAiming = true;
            Time.timeScale = 0.5f;
        }
        if (Input.GetMouseButtonUp(0) && IsAiming)
        {
            IsAiming = false;
            Time.timeScale = 1f;
            player.b_wantDash = true;
        }
        if (Input.GetMouseButtonDown(1) && IsAiming)
        {
            IsAiming = false;
            Time.timeScale = 1f;
        }
    }

    private void FixedUpdate()
    {
        if (!b_isActive)
            return;
    }   
}